package com.home.jinlanhua.exception;

/**
 * @program: jinlanhua
 * @description:
 * @author: Mr.Wang
 * @create: 2020-07-07 02:26
 **/

import com.home.jinlanhua.constant.AllCode;
import com.home.jinlanhua.result.Result;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.function.Supplier;

/**
 * 捕获异常的类，返回信息给浏览器，可以自定义返回的code,msg等信息
 */
@ControllerAdvice
public class MyExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        if (e instanceof CustomerException) {   //判断异常是否是我们定义的异常
            CustomerException customerException = (CustomerException) e;
            AllCode allCode = customerException.getAllCode();
            return Result.error(allCode.getCode(), allCode.getMessage());
        }else {
            logger.error(new Supplier<String>() {
                @Override
                public String get() {
                    return "【未知错误】";
                }
            },e);
            return Result.error(-1, "未知错误");
        }
    }
}
